package com.firebird.fejpsl.controller.app;

import com.firebird.fejpsl.base.BaseApiController;
import com.firebird.fejpsl.base.RestResponse;
import com.firebird.fejpsl.domain.app.Banner;
import com.firebird.fejpsl.service.app.BannerService;
import com.firebird.fejpsl.utility.PageInfoHelper;
import com.firebird.fejpsl.viewmodel.app.banner.BannerEditRequestVM;
import com.firebird.fejpsl.viewmodel.app.banner.BannerPageRequestVM;
import com.firebird.fejpsl.viewmodel.app.banner.BannerResponseVM;
import com.github.pagehelper.PageInfo;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController("AppBannerController")
@RequestMapping(value = "/api/app")
@AllArgsConstructor
public class BannerController extends BaseApiController {

    private final BannerService bannerService=null;

    @RequestMapping(value = "/banner/list", method = RequestMethod.POST)
    public RestResponse<List<Banner>> list() {
        List<Banner> banners = bannerService.allBanner();
        return RestResponse.ok(banners);
    }

    @RequestMapping(value = "/banner/page", method = RequestMethod.POST)
    public RestResponse<PageInfo<BannerResponseVM>> pageList(@RequestBody BannerPageRequestVM model) {
        PageInfo<Banner> pageInfo = bannerService.page(model);
        PageInfo<BannerResponseVM> page = PageInfoHelper.copyMap(pageInfo, e -> modelMapper.map(e, BannerResponseVM.class));
        return RestResponse.ok(page);
    }

    @RequestMapping(value = "/banner/edit", method = RequestMethod.POST)
    public RestResponse edit(@RequestBody @Valid BannerEditRequestVM model) {
        Banner banner = modelMapper.map(model, Banner.class);
        if (model.getId() == null) {
            banner.setDeleted(false);
            bannerService.insertByFilter(banner);
        } else {
            bannerService.updateByIdFilter(banner);
        }
        return RestResponse.ok();
    }

    @RequestMapping(value = "/banner/select/{id}", method = RequestMethod.POST)
    public RestResponse<BannerEditRequestVM> select(@PathVariable Integer id) {
        Banner banner = bannerService.selectById(id);
        BannerEditRequestVM vm = modelMapper.map(banner, BannerEditRequestVM.class);
        return RestResponse.ok(vm);
    }

    @RequestMapping(value = "/banner/delete/{id}", method = RequestMethod.POST)
    public RestResponse delete(@PathVariable Integer id) {
        Banner banner = bannerService.selectById(id);
        banner.setDeleted(true);
        bannerService.updateByIdFilter(banner);
        return RestResponse.ok();
    }
}
